/**
 * 组合 treeData 数据
 */
export const parse = (list = []) =>
    list.map(_ => ({
        ..._,
        key: _.id.toString(),
        title: _.menuName,
        children: _.children ? parse(_.children) : null
    }));
/**
 * 扁平化树结构
 * @param {*}
 * @returns [{key,title}]
 */
export const treeToLine = data => {
    const dataList = [];
    const deep = tree => {
        for (let i = 0; i < tree.length; i += 1) {
            const node = tree[i];
            dataList.push(node);
            if (node.children) {
                deep(node.children);
            }
        }
    };
    deep(data);
    return dataList;
};
/**
 * 获取根节点的key (没看懂...)
 * */
export const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i += 1) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};
/**
 * 获取所有的父节点
 * @param {*} key
 * @param {*} tree
 */
export function getParentList(key, tree) {
    let parentIds = [];
    const setParentIds = (K, data, parentNode) => {
        if (data) {
            return data.map(item => {
                const newItem = {
                    ...item,
                    parentIds: parentNode ? parentNode.parentIds : [],
                    children: setParentIds(K, item.children, {
                        ...item,
                        parentIds: parentNode ? [...parentNode.parentIds, item.key] : [item.key]
                    })
                };
                return newItem;
            });
        }
        return [];
    };
    const tmpData = setParentIds(key, tree);

    const findById = (K, data) => {
        if (data) {
            data.forEach(item => {
                if (item.key === K) {
                    const { parentIds: tmp } = item;
                    parentIds = tmp;
                } else if (item.children) {
                    findById(key, item.children);
                }
            });
        }
    };

    findById(key, tmpData);

    return parentIds;
}
/**
 * 点击父节点 获取所有子节点id [11,222]
 * @param node 当前点击的 node
 */
export const getChildrenList = (node, keys) => {
    if (node.children) {
        node.children.forEach(item => {
            keys.push(item.key);
            if (item.children) {
                getChildrenList(item, keys);
            }
        });
    }
};
/**
 * 字符串首尾加空格
 */
export const addStirng = strs => {
    if (strs) {
        return `,${strs},`;
    }
    return strs;
};
